package com.sky.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.constant.StatusConstant;
import com.sky.dto.DishDTO;
import com.sky.dto.DishPageQueryDTO;
import com.sky.entity.Dish;
import com.sky.entity.DishFlavor;
import com.sky.entity.Setmeal;
import com.sky.exception.DeletionNotAllowedException;
import com.sky.mapper.DishFlavorMapper;
import com.sky.mapper.DishMapper;
import com.sky.mapper.SetmealDishMapper;
import com.sky.mapper.SetmealMapper;
import com.sky.result.PageResult;
import com.sky.service.DishService;
import com.sky.vo.DishVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

@Slf4j
@Service
public class DishServiceImpl implements DishService {
    @Autowired
    private DishMapper dishMapper;
    @Autowired
    private DishFlavorMapper dishFlavorMapper;
    @Autowired
    private SetmealDishMapper setmealDishMapper;
    @Autowired
    private SetmealMapper setmealMapper;

    @Transactional
    public void addDish(DishDTO dishDTO) {
        log.info("新增菜品：{}", dishDTO);
        // 1.构造菜品基本信息数据，将其存入dish表中
        Dish dish = new Dish();
        // 拷贝属性值
        BeanUtils.copyProperties(dishDTO, dish);
        // 保存菜品基本信息
        dishMapper.insert(dish);
        log.info("dishId={}", dish.getId());
        // 2.构造菜品口味列表数据，将其存入dish_flavor表中
        List<DishFlavor> dishFlavors = dishDTO.getFlavors();
        if(dishFlavors != null && dishFlavors.size() > 0) {
            dishFlavors.forEach(dishFlavor -> {
                // 设置菜品id
                dishFlavor.setDishId(dish.getId());
            });
            // 保存菜品口味数据
            dishFlavorMapper.insertFlavors(dishFlavors);
        }
    }

    @Override
    public PageResult page(DishPageQueryDTO dishPageQueryDTO) {
        // 1.构造分页查询条件
        PageHelper.startPage(dishPageQueryDTO.getPage(), dishPageQueryDTO.getPageSize());
        // 2.执行分页查询
        Page<DishVO> dishList = dishMapper.list(dishPageQueryDTO);
        // 3.构造分页结果
        return new PageResult(dishList.getTotal(), dishList.getResult());
    }

    @Transactional
    @Override
    public void deleteDish(List<Long> ids) {
        // 1.删除菜品之前，需要判断菜品是否启售，启售中不允许删除
        ids.forEach(id -> {
            Dish dish = dishMapper.selectById(id);
            if(dish.getStatus() == StatusConstant.ENABLE) {
                throw new DeletionNotAllowedException(MessageConstant.DISH_ON_SALE);
            }
        });

        // 2.需要判断菜品是否被套餐关联，关联了也不允许删除
        Integer count = setmealDishMapper.countBySetmeal(ids);
        if (count > 0) {
            throw new DeletionNotAllowedException(MessageConstant.DISH_BE_RELATED_BY_SETMEAL);
        }

        // 3.删除菜品基本信息 dish表
        dishMapper.deleteByIds(ids);
        // 4.删除菜品口味列表信息 dish_flavor表
        dishFlavorMapper.deleteByIds(ids);
    }

    @Override
    public DishVO getById(Long id) {
        // 1.查询菜品基本信息
        DishVO dishVO = new DishVO();
        Dish dish = dishMapper.selectById(id);

        BeanUtils.copyProperties(dish, dishVO);
        // 2.查询菜品口味列表信息
        List<DishFlavor> dishFlavors = dishFlavorMapper.selectByDishId(id);
        dishVO.setFlavors(dishFlavors);
        // 3.构造菜品VO对象
        return dishVO;
    }

    @Transactional
    @Override
    public void updateDish(DishDTO dishDTO) {
        Dish dish = new Dish();
        BeanUtils.copyProperties(dishDTO, dish);
        // 1.修改基本信息
        dishMapper.updateById(dish);
        // 2.修改口味列表
        dishFlavorMapper.deleteByIds(Arrays.asList(dish.getId()));
        List<DishFlavor> dishFlavors = dishDTO.getFlavors();
        if(dishFlavors != null && dishFlavors.size() > 0) {
            dishFlavors.forEach(dishFlavor -> {
                dishFlavor.setDishId(dish.getId());
            });
            dishFlavorMapper.insertFlavors(dishFlavors);
        }
    }

    /**
     * 根据分类id查询菜品列表
     * @param categoryId
     * @param name
     * @return
     */
    @Override
    public List<Dish> getByCategoryId(Long categoryId, String name) {
        return dishMapper.getByCategoryId(categoryId, name);
    }

    /**
     * 条件查询菜品和口味
     * @param dish
     * @return
     */
    public List<DishVO> listWithFlavor(Dish dish) {
        List<Dish> dishList = dishMapper.listBy(dish);

        List<DishVO> dishVOList = new ArrayList<>();

        for (Dish d : dishList) {
            DishVO dishVO = new DishVO();
            BeanUtils.copyProperties(d,dishVO);

            //根据菜品id查询对应的口味
            List<DishFlavor> flavors = dishFlavorMapper.selectByDishId(d.getId());

            dishVO.setFlavors(flavors);
            dishVOList.add(dishVO);
        }

        return dishVOList;
    }

    /**
     * 菜品启售、停售
     * @param status
     * @param id
     */
    @Transactional
    public void startOrStop(Integer status, Long id) {
        Dish dish = Dish.builder()
                .id(id)
                .status(status)
                .build();
        dishMapper.updateById(dish);

        // 如果是停售操作，还需要将包含当前菜品的套餐也停售
        if (status.equals(StatusConstant.DISABLE)) {
            // 联表查询setmeal、dish、setmeal_dish
            List<Setmeal> setmealList = setmealMapper.getByDishId(id);
            for (Setmeal setmeal : setmealList) {
                if (setmeal != null) {  //有关联的套餐才需要执行update操作，注意判空处理，否则NPE
                    setmeal.setStatus(StatusConstant.DISABLE);
                    setmealMapper.update(setmeal);
                }
            }
        }
    }
}
